/**
 * 最终验证测试 - 验证所有修复是否生效
 */

import { MastraClient } from '@mastra/client-js';

console.log('🚀 开始最终验证测试...\n');

const mastraClient = new MastraClient({
  baseUrl: 'http://localhost:4111',
  retries: 3,
  backoffMs: 300,
  maxBackoffMs: 5000,
});

async function testGameFlow() {
  try {
    console.log('📋 测试完整游戏流程...');
    
    const agent = mastraClient.getAgent('gameMasterAgent');
    const result = await agent.generateVNext({
      messages: [
        {
          role: 'user',
          content: `请开始一个新的赛博侦探游戏。

游戏配置：
- 难度：normal
- 主题：办公室谋杀案
- 嫌疑人数量：3
- 玩家档案：{"name": "最终测试侦探", "experience": "专家"}

请使用 game-master 工具执行 start_game 操作。`
        }
      ]
    });

    console.log('✅ Agent响应成功');
    console.log('📝 响应文本长度:', result.text?.length || 0);
    
    // 等待工具调用完成
    const toolResults = await result.toolResults;
    console.log('🔧 工具调用数量:', toolResults?.length || 0);
    
    if (toolResults && toolResults.length > 0) {
      const toolResult = toolResults[0];
      console.log('🎯 工具调用成功');
      
      if (toolResult.payload?.result) {
        const gameData = toolResult.payload.result;
        console.log('📊 游戏数据验证:');
        console.log('- success:', gameData.success);
        console.log('- data存在:', !!gameData.data);
        console.log('- sessionInfo存在:', !!gameData.sessionInfo);
        
        if (gameData.data) {
          console.log('\n🎮 案件数据详情:');
          console.log('- sessionId:', gameData.data.sessionId);
          console.log('- caseData存在:', !!gameData.data.caseData);
          
          if (gameData.data.caseData) {
            const caseData = gameData.data.caseData;
            console.log('- case存在:', !!caseData.case);
            console.log('- suspects存在:', !!caseData.suspects);
            console.log('- initialClues存在:', !!caseData.initialClues);
            
            if (caseData.case) {
              console.log('\n📋 案件信息:');
              console.log('- 标题:', caseData.case.title);
              console.log('- 地点:', caseData.case.location);
              console.log('- 受害者:', caseData.case.victim);
              console.log('- 真凶ID:', caseData.case.culpritId);
            }
            
            if (caseData.suspects) {
              console.log('\n👥 嫌疑人信息:');
              console.log('- 数量:', caseData.suspects.length);
              caseData.suspects.forEach((suspect, index) => {
                console.log(`  ${index + 1}. ${suspect.name} - ${suspect.personality} (可疑度: ${suspect.suspicionLevel}/10)`);
                if (suspect.isCulprit) {
                  console.log(`     🔍 真凶: ${suspect.name}`);
                }
              });
            }
            
            if (caseData.initialClues) {
              console.log('\n🔍 初始线索:');
              console.log('- 数量:', caseData.initialClues.length);
              caseData.initialClues.forEach((clue, index) => {
                console.log(`  ${index + 1}. ${clue.description} (重要性: ${clue.importance}/5)`);
              });
            }
          }
        }
        
        return {
          success: true,
          gameData,
          message: '完整游戏流程测试成功'
        };
      } else {
        console.log('❌ 工具结果中没有payload.result');
        return {
          success: false,
          error: 'NO_PAYLOAD_RESULT'
        };
      }
    } else {
      console.log('❌ 没有工具调用结果');
      return {
        success: false,
        error: 'NO_TOOL_RESULTS'
      };
    }

  } catch (error) {
    console.error('❌ 测试失败:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

async function testNetworkStability() {
  console.log('\n📋 测试网络稳定性...');
  
  const results = [];
  const testCount = 3;
  
  for (let i = 1; i <= testCount; i++) {
    try {
      console.log(`   测试 ${i}/${testCount}...`);
      
      const agent = mastraClient.getAgent('gameMasterAgent');
      const startTime = Date.now();
      
      const result = await agent.generateVNext({
        messages: [
          {
            role: 'user',
            content: `快速测试 ${i}: 请开始一个简单的推理游戏。难度：easy，主题：办公室，嫌疑人：2。请使用 game-master 工具执行 start_game 操作。`
          }
        ]
      });
      
      const responseTime = Date.now() - startTime;
      const toolResults = await result.toolResults;
      
      const success = !!(toolResults && toolResults.length > 0 && toolResults[0].payload?.result);
      
      results.push({
        test: i,
        success,
        responseTime,
        hasToolResults: !!(toolResults && toolResults.length > 0)
      });
      
      console.log(`   测试 ${i}: ${success ? '✅ 成功' : '❌ 失败'} (${responseTime}ms)`);
      
      // 短暂延迟避免过快请求
      await new Promise(resolve => setTimeout(resolve, 1000));
      
    } catch (error) {
      console.log(`   测试 ${i}: ❌ 失败 - ${error.message}`);
      results.push({
        test: i,
        success: false,
        error: error.message
      });
    }
  }
  
  const successCount = results.filter(r => r.success).length;
  const avgResponseTime = results
    .filter(r => r.responseTime)
    .reduce((sum, r) => sum + r.responseTime, 0) / results.filter(r => r.responseTime).length;
  
  console.log(`\n📊 网络稳定性测试结果:`);
  console.log(`- 成功率: ${successCount}/${testCount} (${Math.round(successCount/testCount*100)}%)`);
  console.log(`- 平均响应时间: ${Math.round(avgResponseTime)}ms`);
  
  return {
    successRate: successCount / testCount,
    averageResponseTime: avgResponseTime,
    results
  };
}

async function runFinalVerification() {
  console.log('🎯 开始最终验证测试...\n');
  
  const gameFlowResult = await testGameFlow();
  const networkStabilityResult = await testNetworkStability();

  console.log('\n' + '='.repeat(60));
  console.log('📊 最终验证测试报告');
  console.log('='.repeat(60));

  console.log(`🎮 完整游戏流程: ${gameFlowResult.success ? '✅ 成功' : '❌ 失败'}`);
  console.log(`🌐 网络稳定性: ${networkStabilityResult.successRate >= 0.8 ? '✅ 良好' : '⚠️ 需要改进'} (${Math.round(networkStabilityResult.successRate * 100)}%)`);
  console.log(`⏱️  平均响应时间: ${Math.round(networkStabilityResult.averageResponseTime)}ms`);

  const overallSuccess = gameFlowResult.success && networkStabilityResult.successRate >= 0.8;

  if (overallSuccess) {
    console.log('\n🎉 最终验证测试完全通过！');
    console.log('✅ 所有修复都已生效');
    console.log('✅ 案件生成Agent工具调用正常');
    console.log('✅ 网络超时问题已解决');
    console.log('✅ 系统稳定性良好');
    console.log('🚀 系统已准备好进行生产使用！');
  } else {
    console.log('\n⚠️  验证测试发现问题:');
    if (!gameFlowResult.success) {
      console.log(`- 游戏流程问题: ${gameFlowResult.error}`);
    }
    if (networkStabilityResult.successRate < 0.8) {
      console.log(`- 网络稳定性问题: 成功率仅${Math.round(networkStabilityResult.successRate * 100)}%`);
    }
    console.log('🔧 需要进一步调试和优化');
  }

  console.log('\n🔧 修复总结:');
  console.log('- 更新了案件生成Agent的工具调用方式');
  console.log('- 修复了toolResults的异步处理');
  console.log('- 添加了超时和重试机制');
  console.log('- 完善了降级方案');
  console.log('- 强化了Agent指令的明确性');

  console.log('\n' + '='.repeat(60));
  return {
    gameFlow: gameFlowResult,
    networkStability: networkStabilityResult,
    overallSuccess
  };
}

runFinalVerification().catch(error => {
  console.error('❌ 最终验证测试失败:', error);
  process.exit(1);
});
